#ifndef __RefCounted_hpp__
#define __RefCounted_hpp__

namespace ge {

//----------------------------------------------------------------------------//
// ReferenceCounted
//----------------------------------------------------------------------------//

class WeakReference;

class ReferenceCounted
{
 public:

     ReferenceCounted( void ) : m_refcnt( 0 ), m_weakref( 0 )
     {
          ++ ms_total_count;
     }

     void AddRef( void ) const
     {
          ++ m_refcnt;
     }

     bool Release( void ) const
     {
          if( !( -- m_refcnt ) )
          {
               delete this;
               return true;
          }

          return false;
     }

     int ReferencesCount( void ) const
     {
          return m_refcnt;
     }

     static int TotalCount( void )
     {
          return ms_total_count;
     }

     virtual WeakReference* GetWeakRef( void ) const
     {
          const_cast< ReferenceCounted* >( this ) -> _InitWeakRef();
          return m_weakref;
     }

 protected:

     virtual ~ReferenceCounted( void )
     {
          _DeinitWeakRef();
          -- ms_total_count;
     }

     void _InitWeakRef( void );
     void _DeinitWeakRef( void );

     mutable int m_refcnt;
     mutable WeakReference* m_weakref;

 private:

     ReferenceCounted( const ReferenceCounted& ); // no source
     ReferenceCounted& operator = ( const ReferenceCounted& ); // no source

     static int ms_total_count;
};


} // namespace ge

#endif//__RefCounted_hpp__
